/**
 * Created by Administrator on 2018/5/18.
 */
define(function (require,exports,module) {
    var sTpl = require("./deptMgr.html");
    require("./deptMgr.css");

    var VueComponent = Vue.extend({
        template: sTpl,
        data :function () {
            return {
                contextPath:"",
                routeType:this.$route.params.type,
                formData:{
                    teamLevel:1,
                    parentCode:'',
                    parentName:'',
                    remark:'',
                    teamLevel:'',
                    remark:'',
                    teamName:'',
                    teamStatus:'',
                    teamId:''
                } ,
                userRole:false,
                update:false,
                teamStatus:false,
                currentUser:{},
                formInput:{user:""},
                formLabelWidth: '120px',
                internalData: [],
                activeNames:['1','2'],
                teams:[],
                currentDept:{},
                myRoles:[],
                dataRoles:[],
                myUsers:[],
                dutyPerson:[],
                myDutyPerson:[],
                dataUsers:[],
                dialogVisible:false,
                dialogVisible2:false,
                dialogDuty:false,
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                editFormVisible:false,
                editFormTitle:'新增部门',
                options: [{
                    value: '1',
                    label: '10人以下'
                }, {
                    value: '2',
                    label: '10~100人'
                }, {
                    value: '3',
                    label: '100人以上'
                }],
                urls:{
                    url:this.contextPath+"/api/webframe/fwteam",
                    initurl:"/api/webframe/fwteam",
                },
                rules: {
                    teamCode: [
                        {required: true, message: '请输入部门编码', trigger: 'blur'}
                    ],
                    teamName: [
                        {required: true, message: '请输入部门名称', trigger: 'blue'}
                    ]
                }
            }
        },
        mounted:function(){
            this.queryTeam();
        },
        methods: {
            getContextPath:function(){
                var contextPath = document.location.pathname;
                var contextPath = contextPath.split('/')[1];
                var contextPath = "/"+contextPath;
                this.contextPath = contextPath;
            },
            getEmptyForm:function () {
                return {
                    teamLevel:1,
                    parentCode:'',
                    parentName:'',
                    remark:'',
                    teamLevel:'',
                    teamName:'',
                    teamStatus:'',
                    teamId:''
                }
            },
            onSearchFwTeam: function(val){
                var   searchVal =this.formInput.key ||"";
                this.urls.url =this.contextPath+this.urls.initurl+"?key="+searchVal;
            },
            addFwTeam:function(row){
                this.currentDept =this.forEachTree(this.teams,row,true) ;
                this.formData=this.getEmptyForm();
                $('.el-input__inner').val('');
                this.formData.teamLevel = parseInt(row.teamLevel)+1;
                this.formData.teamStatus = true;
                this.formData.parentCode=row.teamId;
                this.formData.parentName=row.teamName;
                this.editFormVisible=true;
                this.editFormTitle='新增部门';


            },
            editUser:function (row) {
                this.currentDept =this.forEachTree(this.teams,row,true);
                this.$data.myRoles=row.roleSet?JSON.parse(JSON.stringify(row.roleSet)):[];
                this.$data.myUsers=row.userList?JSON.parse(JSON.stringify(row.userList)):[];
                this.$data.myDutyPerson=row.dutyUser?JSON.parse(JSON.stringify(row.dutyUser)):[];
                this.$data.dutyPerson=row.userList?JSON.parse(JSON.stringify(row.userList)):[];

            },
            forEachTree:function (array,value,ret) {
                var $this = this;

                var returnValue;
                for(var i=0;i<array.length;i++){
                    var data = array[i];
                    console.log(data.teamName)
                    if(returnValue){
                        return returnValue;
                    }
                    if(data.teamId==value.teamId){
                        if(!ret){
                            array[i] = value;
                        }
                        returnValue=array[i];
                        break;
                    }else{
                        if(data.children)
                            returnValue= $this.forEachTree(data.children,value,ret);
                    }
                }
                return returnValue;

            },
            rowClick:function(row, event, column){
                this.$refs.table.$children[0].clearSelection();
                this.$refs.table.$children[0].toggleRowSelection(row);
                this.initUserRolesAndUsers();
            },
            handleEdit:function(val){
                this.update= false;
                this.formData =this.forEachTree(this.teams,val,true) ;
                this.formData.teamStatus = this.formData.teamStatus==1;
                this.editFormVisible=true;
                this.editFormTitle='编辑部门';
            },
            handleDelete:function(val){
                this.formData =this.forEachTree(this.teams,val,true) ;
                var $this= this;
                if(this.formData.children){
                    var data;
                    for(var i=0;i<this.formData.children.length ,data=this.formData.children[i];i++)
                        if(data.teamStatus==1){
                            $this.$notify({"title":"删除失败",message:"请先删除子部门"});
                            return;
                        }
                }
                this.$confirm('确定要删除该部门？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(function() {
                    $this.formData.teamStatus =0;
                    $this.submitData(function () {
                        var parent=$this.forEachTree($this.teams,{teamId:$this.formData.parentCode},true);
                        for(var i=0;i<parent.children.length;i++){
                            if(parent.children[i].teamId==$this.formData.teamId){
                                parent.children.splice(i, 1);
                                return;
                            }
                        }
                        self.$notify({title:"删除成功",message:"部门删除成功"})
                    });
                })
            },
            formCancle:function(){
                this.$refs.table.dialogFormVisible=false;
            },
            selectionChange:function(val){
                this.internalData = val;
            },
            handleChange:function(){
                return;
            },
            singleSelect:function(){
                if(this.internalData.length!=1){
                    this.$message({
                        type: 'error',   message: '请选择一条记录!'
                    });
                    return false;
                }
                return true;
            },

            handleFormClose:function () {
                if(this.$refs.editForm){
                    this.$refs.editForm.resetFields();
                }
            },
            handleCloseForm:function () {

                    this.editFormVisible=false;



            },
            submitData:function (callback) {
                var self = this;
                self.update=true;
                self.editFormVisible=false;
                self.formData.teamStatus = self.formData.teamStatus?"1":"0";
                axios.post(self.contextPath+self.urls.initurl,self.formData).then(function (response) {
                    var data=response.data;
                    if(!self.formData.teamId){
                        self.$notify({title:"添加成功",message:"部门添加成功"})
                        data.id=data.teamId;
                        data.parent_id = data.parentCode;
                        data.label=data.teamName;
                        self.currentDept.expanded=true;
                        if(!self.currentDept.children){
                            self.currentDept.children=[];
                        }
                        self.currentDept.children.push(data);
                        //self.forEachTree(self.teams,self.currentDept);
                    }else{
                        if(callback){
                            callback();
                        }else{
                            self.$notify({title:"修改成功",message:"部门修改成功"})
                        }

                        //self.forEachTree(self.teams,self.formData);
                    }
                    self.teams.forEach(function (d,i) {
                        self.$set(self.teams,i,self.teams[i]);
                    });
                })

            },
            formConfirm:function(){
                var self = this;
                this.$refs.editForm.validate(function (valid) {
                    if(valid){
                        self.submitData();
                    }
                });
            },
            updateUserRole:function (scope) {
                var $this = this;
                // this.currentDept.userList.forEach(
                //     function(user){
                //         if(user.userId==scope.row.userId){
                //             $this.currentUser = user;
                //         }
                //     })
                $this.currentUser = scope.row;
                $this.$data.userRole = true;
            },
            confirmUserRoles:function(){
                this.userRole = false
                var $this = this;
                this.currentDept.userList.forEach(
                    function(user){
                        if(user.userId==$this.currentUser.userId){
                           user.roles = $this.currentUser.roles;
                        }
                    }
                )

                axios.post(basepath+'/api/webframe/fwteam/updateFwRoleTeamByTeamId',$this.currentUser).then(function(result){
                    this.currentDept.roleSet=this.$data.myRoles;
                }.bind(this));
            },
            handleCloseDuty:function () {
                self.$data.dialogDuty = false;
            } ,
            handleCloseUserRole:function(){
                self.$data.userRole = false;
            },
            handleCloseRole:function(){
                self.$data.dialogVisible2 = false;
            },
            handleCloseUser:function(){
                self.$data.dialogVisible = false;
            },
            initUserRolesAndUsers:function(){
                var contextPath = this.contextPath;
                var teamId = this.currentDept.teamId+"";
                axios.get(contextPath+'/api/webframe/fwrole/transferByTeam/'+teamId).then(function(result){
                    this.$data.dataRoles=result.data.dataRoles;
                    this.$data.myRoles=result.data.myRoles;
                }.bind(this));
                axios.get(contextPath+'/api/webframe/fwuser/transferByTeam/'+teamId).then(function(result){
                    this.$data.dataUsers=result.data.dataUsers;
                    this.$data.myUsers=result.data.myUsers;
                }.bind(this));
            },
            confirmRoles:function(){
                this.dialogVisible2 = false
                var data = {
                    "roleIds":this.$data.myRoles.map(function(data){return data.roleId }),
                    "teamId":this.currentDept.teamId+""
                }

                var contextPath = this.contextPath;
                axios.post(contextPath+'/api/webframe/fwteam/updateFwRoleTeamByTeamId',data).then(function(result){
                    this.currentDept.roleSet=this.$data.myRoles;
                }.bind(this));
            },
            confirmDutyUsers:function () {
                this.dialogDuty = false
                var data = {
                    "users":this.$data.myDutyPerson,
                    "team":this.currentDept.teamId+""
                }
                var data =JSON.parse(JSON.stringify(this.currentDept));
                data.dutyUser = this.myDutyPerson;
                axios.post(basepath+'/api/webframe/fwteam/updateFwTeamDuty',data).then(function(result){
                    this.currentDept.dutyUser=JSON.parse(JSON.stringify(this.$data.myDutyPerson));
                }.bind(this));
            },
            confirmUsers:function(){
                this.dialogVisible = false
                var data = {
                    "users":this.$data.myUsers,
                    "teamId":this.currentDept.teamId+""
                }
                var contextPath = this.contextPath;
                axios.post(contextPath+'/api/webframe/fwuser/updateFwTeamUserByTeamId',data).then(function(result){
                    this.currentDept.userList=JSON.parse(JSON.stringify(this.$data.myUsers));
                }.bind(this));
            },
            queryTeam:function () {
                var $this = this;

                axios.get(this.contextPath+"/api/webframe/fwteam/queryAllTeamsNopage?all="+this.teamStatus).then(function(response){
                    var teams = {};
                    $this.teams =[];
                    response.data.sort(function(val ,val2){
                        return val.teamName >val2.teamName?-1:1;
                    })
                    response.data.forEach(function(data){
                        if(data.teamLevel==1){
                            $this.teams.push(data);
                        };
                        teams[data.teamId]=data;
                        if(data.teamLevel<2){
                            data.expanded=true
                        }else{
                            data.expanded=false;
                        }

                        data.id=data.teamId;
                        data.parent_id = data.parentCode;
                        data.label=data.teamName;
                    });
                    response.data.forEach(function(data){
                        if(data.parentCode&&teams[data.parentCode]){
                            if(!teams[data.parentCode].children){
                                teams[data.parentCode].children=[];
                                //teams[data.parentCode].expanded=true;
                            }
                            teams[data.parentCode].children.unshift(data);
                        }
                    });

                });
            }
        },
        watch:{
            teamStatus:function (nv ,ov) {
                this.queryTeam();
            },
            editFormVisible:function(nv,ov){
                if(!nv ){
                    if(!this.update){
                        this.$refs.editForm.resetFields();
                    }
                    // this.teams.forEach(function (d,i) {
                    //     self.$set(self.teams,i,self.teams[i]);
                    // });
                }
            }
        },
        created:function (){
            this.getContextPath();
            var $this = this;
            this.urls.url = this.contextPath+"/api/webframe/fwteam/?key=";
            axios.get(basepath+'/api/webframe/fwrole/transferByTeam/'+"1").then(function(result){
                this.$data.dataRoles=result.data.dataRoles;
            }.bind(this));
            axios.get(basepath+'/api/webframe/fwuser/transferByTeam/'+"1").then(function(result){
                this.$data.dataUsers=result.data.dataUsers;
            }.bind(this));

            window.self = this;


        },
        activated:function () {
            messages.$emit('change','部门管理');
        }

    });
    module.exports = VueComponent;
})
